/**
 * Copyright 2016 JustWayward Team
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.htfyun;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.OwnerSurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.htfyun.pdfview.GraffitiView;
import com.htfyun.pdfview.IPWSurfaceView;
import com.htfyun.pdfview.PWSurfaceOfGrafftiView;
import com.htfyun.pdfview.PWSurfaceOfOwnerSurfaceView;
import com.htfyun.pdfview.PdfViewManager;
import com.htfyun.utils.DebugLog;
import com.htfyun.utils.DisplayUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.geometerplus.android.fbreader.api.FBReaderIntents;
import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
import org.geometerplus.fbreader.book.Book;
import org.geometerplus.fbreader.book.Bookmark;
import org.geometerplus.zlibrary.core.util.RationalNumber;
import org.geometerplus.zlibrary.ui.android.BuildConfig;
import org.geometerplus.zlibrary.ui.android.R;

import java.io.File;

import io.apptik.widget.MultiSlider;
import uk.co.senab.photoview.PhotoViewAttacher;

@EActivity(R.layout.htfyun_activity_pdf_system)
public class ReadPDFActivity extends AppCompatActivity {

    public static void start(Context context, String filePath) {
        Intent intent = new Intent(context, ReadPDFActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.fromFile(new File(filePath)));
        context.startActivity(intent);
    }

    private BookCollectionShadow myCollection;
    private volatile Book myBook;

    @ViewById
    RelativeLayout layoutRoot;
    
    @ViewById
    View toolbar;
    
    @ViewById
    TextView toolbarTitle;
    
    @ViewById
    ImageView llPdfRoot;
    
//    @ViewById
//    IPWSurfaceView pwdraw_surface_view;

//    @ViewById
//    GraffitiView pwdraw_surface_view;

    @ViewById
    View layoutFunc;
    
    @ViewById
    TextView txtPdfPostilHide;
    
    @ViewById
    View layoutPW;
    
    @ViewById
    TextView txtPdfProgress;
    @ViewById
    MultiSlider slider;

    private PdfViewManager pdfViewManager;

    private PopupWindow popupWindowShape;
    private PopupWindow popupWindowLineWidth;

    private IPWSurfaceView pwdraw_surface_view;

    @ViewById
    ImageView imgPWShape;
    @ViewById
    ImageView imgPWLineWidth;

    @Click(R.id.txtPdfPostil)
    void onClick_txtPdfPostil(){

        pwdraw_surface_view.setVisibility(View.VISIBLE);
        pwdraw_surface_view.setHostView(llPdfRoot);
        pwdraw_surface_view.setDrawObjectType(IPWSurfaceView.DRAW_OBJ_RANDOM);


        setVisibleOfLayoutPW(true);
      
    }

    @Click(R.id.txtPdfPostilHide)
    void onClick_txtPdfPostilHide(){

        if (pdfViewManager == null) {
            return;
        }
        
        pdfViewManager.setShowNote(!pdfViewManager.isShowNote());
        txtPdfPostilHide.setText(pdfViewManager.isShowNote() ? R.string.pdf_pw_note_hide : R.string.pdf_pw_note_show);

    }

    @Click(R.id.toolbarLeftImg)
    void onClick_toolbarLeftImg() {
        
        finish();
    }
    
    @Click(R.id.previous)
    void onClick_previous() {
        
        doPrevious();
        
    }

    @Click(R.id.next)
    void onClick_next() {
        
        doNext();

    }

    @Click(R.id.imgPWShape)
    void onClick_imgPWShape() {

        if (popupWindowShape == null) {
            initShape();
        }

        showPopupWindow(popupWindowShape);
        popupWindowShape.showAsDropDown(imgPWShape, 0, 0);

    }

    @Click(R.id.imgPWLineWidth)
    void onClick_imgPWLineWidth() {
        if (popupWindowLineWidth == null) {
            initLineWidth();
        }

        showPopupWindow(popupWindowLineWidth);
        popupWindowLineWidth.showAsDropDown(imgPWLineWidth, 0, 0);

    }

    @Click(R.id.imgPWClose)
    void onClick_imgPWClose() {

        pdfViewManager.save(pwdraw_surface_view.getBitmap());
        pwdraw_surface_view.clear();
        pwdraw_surface_view.setVisibility(View.GONE);
        
        pdfViewManager.setCurPosition(pdfViewManager.getCurrentPosition());

        setVisibleOfLayoutPW(false);

    }

    @Click(R.id.imgPWUndo)
    void onClick_imgPWUndo() {

        pwdraw_surface_view.undo();

    }

    @Click(R.id.imgPWSave)
    void onClick_imgPWSave() {
        pdfViewManager.save(pwdraw_surface_view.getBitmap());
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        
        super.onCreate(savedInstanceState);

        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN
        );
    }

    @AfterViews
    void afterViews() {

        if (BuildConfig.USE_PHONE) {
            GraffitiView view = new GraffitiView(this, null);
            view.setBackgroundColor(Color.TRANSPARENT);

            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.addRule(RelativeLayout.ABOVE, R.id.layoutPW);
            
            layoutRoot.addView(view, layoutParams);
            
            pwdraw_surface_view = new PWSurfaceOfGrafftiView(view);
            
        } else {

            OwnerSurfaceView view =  new OwnerSurfaceView(this, null);
            view.setBackgroundColor(Color.TRANSPARENT);
            
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.addRule(RelativeLayout.ABOVE, R.id.layoutPW);

            layoutRoot.addView(view, layoutParams);
            
            pwdraw_surface_view = new PWSurfaceOfOwnerSurfaceView(view);

        }

        pwdraw_surface_view.setVisibility(View.GONE);

        setVisibleOfLayoutFuncAndToolbar(false);
        setVisibleOfLayoutPW(false);


        myCollection = new BookCollectionShadow();
        myBook = FBReaderIntents.getBookExtra(getIntent(), myCollection);
        if (myBook == null) {
            finish();
        }

        toolbarTitle.setText(myBook.getTitle());


        myCollection.bindToService(this, new Runnable() {
            @Override
            public void run() {
                myCollection.saveBook(myBook);
                myCollection.addToRecentlyOpened(myBook);
            }
        });
        
        DebugLog.e("book id = " + myBook.getId() + ", book path = " + myBook.getPath());
        displayFromFile((myBook.getPath()));

        initSliderAfterDisplayPdf();
        
    }

    private void initSliderAfterDisplayPdf() {

        if (pdfViewManager == null) {
            throw new IllegalStateException("pdfViewManager is null , should init it first!");
        }

        slider.setMin(1);
        slider.setMax(pdfViewManager.getCount());
        slider.setProgress(pdfViewManager.getCurrentPosition());

        setTxtPdfProgress();
        
        slider.setOnTrackingChangeListener(new MultiSlider.OnTrackingChangeListener() {
            @Override
            public void onStartTrackingTouch(MultiSlider multiSlider, MultiSlider.Thumb thumb, int value) {

            }

            @Override
            public void onStopTrackingTouch(MultiSlider multiSlider, MultiSlider.Thumb thumb, int value) {

                pdfViewManager.setCurPosition(value);
                setTxtPdfProgress();

            }
        });
    }

    private void setTxtPdfProgress() {
        if (pdfViewManager == null) {
            return;
        }
        txtPdfProgress.setText(getString(R.string.base_page_number_percent, pdfViewManager.getCurrentPosition() + 1, pdfViewManager.getCount()));
    }
    
    private void setVisibleOfLayoutFuncAndToolbar(boolean visible) {
        layoutFunc.setVisibility(visible ? View.VISIBLE : View.GONE);
        toolbar.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    private void setVisibleOfLayoutPW(boolean visible) {
        if (visible) {
            setVisibleOfLayoutFuncAndToolbar(false);
        }
        layoutPW.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    private void displayFromFile(String filePath) {

        RationalNumber progress = myBook.getProgress();

        pdfViewManager = new PdfViewManager(this, llPdfRoot, filePath, (int) progress.Numerator);
        
        pdfViewManager.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
            @Override
            public void onViewTap(View view, float x, float y) {
              
                x = x / llPdfRoot.getWidth();
                
                if (x < 0.33f) {
                    doPrevious();
                } else if (x >= 0.67f) {
                   doNext();
                } else {
                    middleClick();
                }
            }
        });
    }

    
    private void savePdfProgress(long item, long total) {

        RationalNumber newProgress = RationalNumber.create(item, total);
        if (newProgress == null) {
            return;
        }

        myBook.setProgress(newProgress);
        myCollection.saveBook(myBook);
    }
    
    private void doNext(){

        int item = pdfViewManager.getCurrentPosition();
        int total = pdfViewManager.getCount();

        if (item >= total - 1) {
            return;
        }

        item ++;
        pdfViewManager.setCurPosition(item);

        savePdfProgress(item, total);
        
        setTxtPdfProgress();

        slider.setProgress(pdfViewManager.getCurrentPosition());


    }

    private void doPrevious() {

        int item = pdfViewManager.getCurrentPosition();
        int total = pdfViewManager.getCount();

        if (item <= 0) {
            return;
        }

        item --;
        pdfViewManager.setCurPosition(item);

        savePdfProgress(item, total);

        setTxtPdfProgress();

        slider.setProgress(pdfViewManager.getCurrentPosition());

    }
    
    private void middleClick() {
        
        setVisibleOfLayoutFuncAndToolbar(toolbar.getVisibility() == View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        DebugLog.e("onDestroy");

        if (pdfViewManager != null) {
            pdfViewManager.close();
            pdfViewManager = null;
        }

        if (myCollection != null) {
            myCollection.unbind();
            myCollection = null;

        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            DebugLog.e("onkeydown finish");

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private PopupWindow initPopupWindow(Context context, @LayoutRes int layoutRes) {

        PopupWindow pw = new PopupWindow(context);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity
                .LAYOUT_INFLATER_SERVICE);

        pw.setContentView(inflater.inflate(layoutRes, null));//设置主体布局
        pw.setFocusable(true);
        pw.setAnimationStyle(0);

        pw.setWidth(DisplayUtil.getScreenWidth(context));//宽度200dp
        int height = getResources().getDimensionPixelSize(R.dimen.activity_pw_func_main_height);
        pw.setHeight(height + 10);

        return pw;

    }


    private void initLineWidth() {
        popupWindowLineWidth = initPopupWindow(this, R.layout.htfyun_popup_pw_pen_width);
        View view = popupWindowLineWidth.getContentView();

        final View width0 = view.findViewById(R.id.einkdraw_pen_width_0);
        width0.setOnClickListener(clickListenerLineWidth);

        width0.setTag(IPWSurfaceView.MIN_PEN_WIDTH_PIXEL);

        final View width1 = view.findViewById(R.id.einkdraw_pen_width_1);
        width1.setTag(IPWSurfaceView.MIN_PEN_WIDTH_PIXEL + 1);
        width1.setOnClickListener(clickListenerLineWidth);

        final View width2 = view.findViewById(R.id.einkdraw_pen_width_2);
        width2.setTag(IPWSurfaceView.MIN_PEN_WIDTH_PIXEL + 2);
        width2.setOnClickListener(clickListenerLineWidth);

        final View width3 = view.findViewById(R.id.einkdraw_pen_width_3);
        width3.setTag(IPWSurfaceView.MIN_PEN_WIDTH_PIXEL + 3);
        width3.setOnClickListener(clickListenerLineWidth);

        final View width4 = view.findViewById(R.id.einkdraw_pen_width_4);
        width4.setTag(IPWSurfaceView.MIN_PEN_WIDTH_PIXEL + 4);
        width4.setOnClickListener(clickListenerLineWidth);
    }

    private View.OnClickListener clickListenerLineWidth = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pwdraw_surface_view.setPenSettingWidth((int)v.getTag());
            if (popupWindowLineWidth != null) {
                popupWindowLineWidth.dismiss();
            }
        }
    };

   

    private void initShape() {
        popupWindowShape = initPopupWindow(this, R.layout.htfyun_popup_pw_shape);

        View view = popupWindowShape.getContentView();

        final View obj_pw = view.findViewById(R.id.einkdraw_obj_pw);
        obj_pw.setOnClickListener(clickListenerShape);

        obj_pw.setTag(IPWSurfaceView.DRAW_OBJ_RANDOM);

        final View obj_line = view.findViewById(R.id.einkdraw_obj_line);
        obj_line.setTag(IPWSurfaceView.DRAW_OBJ_LINE);
        obj_line.setOnClickListener(clickListenerShape);

        final View obj_circle = view.findViewById(R.id.einkdraw_obj_circle);
        obj_circle.setTag(IPWSurfaceView.DRAW_OBJ_CIRCLE);
        obj_circle.setOnClickListener(clickListenerShape);

        final View obj_rect = view.findViewById(R.id.einkdraw_obj_rect);
        obj_rect.setTag(IPWSurfaceView.DRAW_OBJ_RECTANGLE);
        obj_rect.setOnClickListener(clickListenerShape);

        final View obj_triangle = view.findViewById(R.id.einkdraw_obj_triangle);
        obj_triangle.setTag(IPWSurfaceView.DRAW_OBJ_TRIANGLE);
        obj_triangle.setOnClickListener(clickListenerShape);

    }


    private View.OnClickListener clickListenerShape = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pwdraw_surface_view.setDrawObjectType((int)v.getTag());
            if (popupWindowShape != null) {
                popupWindowShape.dismiss();
            }
        }
    };

    private void showPopupWindow(PopupWindow popupWindow) {


        int objType = -1;//pwdraw_surface_view.getDrawObjectType();

        if (popupWindow == popupWindowShape) {
            objType = pwdraw_surface_view.getDrawObjectType();
        } else if (popupWindow == popupWindowLineWidth) {
            objType = pwdraw_surface_view.getPenSettingWidth();
        } else {

            return;
        }

        ViewGroup viewGroup = (ViewGroup)popupWindow.getContentView();

        for (int i = 0; i < viewGroup.getChildCount(); i ++) {
            View view = viewGroup.getChildAt(i);
            if (view instanceof ViewGroup) {
                ViewGroup childGroup = (ViewGroup) view;
                for (int j = 0; j < childGroup.getChildCount(); j++) {
                    View childView = childGroup.getChildAt(j);
                    if (!(childView instanceof ImageView)
                            && view.getTag() != null
                            && (view.getTag() instanceof  Integer)) {
                        childView.setVisibility((objType == (int) view.getTag()) ? View.VISIBLE : View.INVISIBLE);
                    }
                }
            }
        }

    }


}
